package com.demo.exception.api;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.demo.exception.constant.SystemConstant;
import com.demo.exception.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * @Description controller层封装返回结果
 * 处理controller之后的逻辑异常
 * 此异常抛出优先于全局异常捕获
 * 1.处理未知的异常
 * 2.封装返回结果集
 * @Author 小乌龟
 * @Date 2022/11/12 15:14
 */
@Slf4j
public class CommonController {


    public <M> CommonResult<M> process(Supplier<M> sp) {
        try {
            M val = sp.get();
            if (ObjectUtils.isEmpty(val)) {
                return CommonResult.failed();
            }
            return CommonResult.success(val);
        } catch (ApiException e) {
           // 此异常抛出优先于全局异常捕获 故抛出自定义异常
            return CommonResult.failed(e.getMessage());
        } catch (Exception e) {
            log.error(this.getClass().getSimpleName(), e);
            log.error(this.getClass().getSimpleName(), e.getLocalizedMessage());
            if (e.getMessage().length() >= SystemConstant.NUM_19) {
                return CommonResult.failed("系统错误 请联系客服");
            }
            return CommonResult.failed(e.getMessage());
        }
    }

}
